#!/usr/bin/env ruby
# Copyright (c) 2021-2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Huawei Technologies Co.,Ltd.

require 'optparse'
require 'yaml'
require 'json'
require 'erb'

module Gen
  def self.on_require(data); end
end

def create_sandbox
  # nothing but Ruby core libs and 'required' files
  binding
end

def check_option(optparser, options, key)
  return if options[key]

  puts "Missing option: --#{key}"
  puts optparser
  exit false
end

def major_minor_version
  major, minor, = RUBY_VERSION.split('.').map(&:to_i)
  [major, minor]
end

def check_version(min_major, min_minor)
  major, minor = major_minor_version
  major > min_major || (major == min_major && minor >= min_minor)
end

def erb_new(str, trim_mode: nil)
  if check_version(2, 6)
    ERB.new(str, trim_mode: trim_mode)
  else
    ERB.new(str, nil, trim_mode)
  end
end

options = OpenStruct.new

optparser = OptionParser.new do |opts|
  opts.banner = 'Usage: gen.rb [options]'

  opts.on('-t', '--template FILE', 'Template for file generation (required)')
  opts.on('-d', '--datafiles FILE1,FILE2,FILE3', Array, 'Source data files in YAML format (required)')
  opts.on('-o', '--output FILE', 'Output file (required)')
  opts.on('-r', '--require foo,bar,baz', Array, 'List of files to be required for generation')

  opts.on('-h', '--help', 'Prints this help') do
    puts opts
    exit
  end
end
optparser.parse!(into: options)

check_option(optparser, options, :datafiles)
check_option(optparser, options, :template)
check_option(optparser, options, :output)

template_file = File.read(File.expand_path(options.template))
output_file = File.open(File.expand_path(options.output), 'w')

options&.require&.each { |r| require File.expand_path(r) } if options.require
require File.expand_path(File.join(File.dirname(__FILE__), 'runtime.rb'))

output_file.puts('# Autogenerated file -- DO NOT EDIT!')
output_file.puts('intrinsics:')

options.datafiles.each do |data|
  if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('3.1.0')
    data = YAML.load_file(File.expand_path(data))
  else
    data = YAML.load_file(File.expand_path(data), aliases: true)
  end
  data = JSON.parse(data.to_json, object_class: OpenStruct)
  Gen.on_require(data)

  t = erb_new(template_file, trim_mode: '%-')
  t.filename = options.template

  output_file.write(t.result(create_sandbox))
end

output_file.close
